package at.fpmedv.eclipse.helma.core;

import helma.framework.repository.Resource;
import helma.objectmodel.db.Relation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;

import at.fpmedv.eclipse.helma.util.ResourceContainer;


public class PropertyTreeObject implements ITreeObject {
	private String name;
	private ITreeParent parent;
	private Relation relation;

	public PropertyTreeObject(String name, Relation propertyRelation, ITreeParent parent) {
		this.name = name;
		this.parent = parent;
		this.relation = propertyRelation;
	}

	public Object getAdapter(Class key) {
		return null;
	}

	public String getName() {
		return name;
	}

	public String getRawName() {
		String result = getName();
		if (result.indexOf("(") != -1) {
			result = result.substring(0, result.indexOf("("));
		}
		return result;
	}

	public String toString() {
		return getName();
	}

	public ITreeParent getParent() {
		return parent;
	}

	public ResourceContainer getResource() {
		Resource result = null;
		int resultLineNumber = 1;
		for (Iterator<Resource> iterRes = parent.getResources().iterator(); iterRes.hasNext();) {
			Resource res = iterRes.next();
			// check if *.properties file
			if (res.getName().endsWith(".properties")) {
				BufferedReader codeReader;
				try {
					InputStream in = res.getInputStream();
					codeReader = new BufferedReader(new InputStreamReader(in));
					int lineNr = 1;
					String line = "";
					// loop through file
					while ((line = codeReader.readLine()) != null) {
						if (line.toLowerCase().startsWith(getRawName() + " ") || line.trim().equals(getRawName())) {
							result = res;
							resultLineNumber = lineNr;
							break;
						}
						lineNr++;
					}
					in.close();
				} catch (IOException e) {
					HelmaCorePlugin.getDefault().log("error reading Resource " + res.toString(), e);
				} catch (NullPointerException e) {
					// HelmaCorePlugin.getDefault().log("error creating input Stream for Resource " + res.toString(), e);
				}
			}
		}
		return new ResourceContainer(result, resultLineNumber);
	}

	public int compare(ITreeObject element, Comparator comparator) {
		/* 
		 * collections second. must be compared here because CollectionTreeObject
		 * are always instanceof PropertyTreeObject
		 */
		if (element instanceof CollectionTreeObject || element instanceof MountPointTreeObject) {
			return -1;
		}
		// sort by name
		if (element instanceof PropertyTreeObject)
			return comparator.compare(this.getName(), element.getName());
		// greater than skin and functions
		return -1;
	}

	public Relation getRelation() {
		return relation;
	}
}